package com.imooc.retrofit;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.OkHttpClient;

public class Retrofit {

    String baseUrl;
    final Call.Factory callFactory;
    final Map<Method,ServiceMethod> serviceMethodMapCache = new ConcurrentHashMap<>();
    public Retrofit(Builder builder) {
        this.baseUrl = builder.baseUrl;
        this.callFactory = builder.callFactory;
    }

    public <T> T create(Class<T> serviceClazz) {
        return (T) Proxy.newProxyInstance(
                serviceClazz.getClassLoader(),
                new Class[]{serviceClazz},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        
                        if (method.getDeclaringClass() == Object.class){
                            return method.invoke(this,args);
                        }
                        
                        // 解析参数注解
                        ServiceMethod servicemethod = loadServiceMethod(method);
                        
                        return null;
                    }
                }
        );
    }

    private ServiceMethod loadServiceMethod(Method method) {
        ServiceMethod serviceMethod = serviceMethodMapCache.get(method);
        if (serviceMethod == null){
            serviceMethod = new ServiceMethod.Builder(this,method).build();
            serviceMethodMapCache.put(method,serviceMethod);
        }
        return serviceMethod;
    }

    public static class Builder{
        String baseUrl;
        private Call.Factory callFactory;
        public Builder baseUrl(String baseUrl){
            this.baseUrl = baseUrl;
            return this;
        }
        public Builder client(Call.Factory callFactory){
            this.callFactory = callFactory;
            return this;
        }
        public Retrofit build(){
            if (callFactory==null){
                callFactory = new OkHttpClient();
            }
            return new Retrofit(this);
        }
    }
}
